package com.tbvtc.agriculturalcreditchainserver2025.controller.user;


import com.tbvtc.agriculturalcreditchainserver2025.utils.aliyuyin.ByteRangeResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/audio")
public class AudioController {



    @GetMapping("/stream/{fileName}")
    public ResponseEntity<Resource> streamAudio(HttpServletRequest request,
                                                @PathVariable String fileName
                                                ) throws IOException {
         final String AUDIO_FILE_PATH = "F:\\DeekSeep\\DK-AI\\src\\main\\resources\\wav\\"+fileName+".wav";


        Resource audioResource = new FileSystemResource(AUDIO_FILE_PATH);

        // 检查文件是否存在
        if (!audioResource.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        // 计算内容长度
        long contentLength = audioResource.contentLength();

        // 支持范围请求的HTTP头
        String rangeHeader = request.getHeader(HttpHeaders.RANGE);
        HttpRange httpRange = rangeHeader != null ?
                HttpRange.parseRanges(rangeHeader).get(0) : // 只处理单个范围请求
                null;

        // 处理范围请求
        if (httpRange != null) {
            long start = httpRange.getRangeStart(contentLength);
            long end = httpRange.getRangeEnd(contentLength);
            long rangeLength = Math.min(1 * 1024 * 1024, end - start + 1); // 每次返回1MB

            // 创建资源区域
            Resource region = new ByteRangeResource(audioResource, start, rangeLength);

            return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + (start + rangeLength - 1) + "/" + contentLength)
                    .body(region);
        }
        // 完整文件请求
        else {
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
                    .body(audioResource);
        }
    }
}